package com.gelian.demo;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

//import com.gelian.demo.engine.GlController;
import com.gelian.demo.utils.BuildStringUtil;
import com.gelian.demo.utils.Toastor;
//import com.gelian.demo.utils.UploadUtil;
import com.gelian.geliansdk.GlEngine;
import com.gelian.geliansdk.GlResultCode;
import com.gelian.geliansdk.callback.GlCallback;
import com.gelian.library.model.GlDevice;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class DeviceActivity extends Activity {
    public static final int REQUEST_CODE_GET_IMG_KITKAT = 998;
    public static final int REQUEST_CODE_GET_IMG_TEST = 997;

    public static final int HANDLER_MSG_SOON = 0x01;


    public static final String TEXT_OPEN_TEST = "启动透传测试";

    public static final String TEXT_CLOSE_TEST = "停止透传测试";

    @Bind(R.id.device_info_tv)
    TextView deviceInfoTv;
    @Bind(R.id.test_tv)
    TextView testTv;
    @Bind(R.id.bind_btn)
    Button bindBtn;

    @Bind(R.id.test_btn)
    Button testBtn;

    @Bind(R.id.send2device_et)
    EditText send2deviceEt;

    @Bind(R.id.receiveServerMsg_tv)
    TextView receiveServerMsgTv;
    @Bind(R.id.set_lenth_et)
    EditText setLenthEt;
    @Bind(R.id.set_hz_et)
    EditText setHzEt;

    private String imei;
    private GlDevice glDevice;

    long successTimes;
    long failTimes;
    int len = 3072;
    int sleep = 500;
    boolean loop;
    int totalTimes;
    String loopMsg = "123456789";

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case HANDLER_MSG_SOON:
                    if (isFinishing()) {
                        return;
                    }
                    testTv.setText("测试总次数:" + totalTimes
                            + ",发送成功:" + successTimes + "次,失败" + failTimes + "次");
                    break;
            }
        }
    };
    Runnable loopRunnable = new Runnable() {
        @Override
        public void run() {
            while (loop) {
                if (glDevice == null) {
                    return;
                }

                send2device(loopMsg + "," + ++totalTimes, callback);
                try {
                    Thread.sleep(sleep);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };
    GlCallback callback = new GlCallback() {
        @Override
        public void done(int resultCode) {
            if (resultCode == GlResultCode.GL_CALLBACK_CODE_SUCCESS) {
                successTimes++;
            } else {
                failTimes++;
            }

            handler.sendEmptyMessage(HANDLER_MSG_SOON);
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device);
        ButterKnife.bind(this);

        EventBus.getDefault().register(this);
        Intent intent = getIntent();
        if (intent == null) {
            finish();
            return;
        }
        glDevice = (GlDevice) intent.getSerializableExtra(GlDevice.class.getSimpleName());
        testBtn.setText(TEXT_OPEN_TEST);
        updateUI(glDevice);
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        loop = false;
        super.onDestroy();
    }

    @Subscriber(tag = AppConstant.NOTIFY_SINGLE_DEVICE_UI)
    protected void updateUI(GlDevice glDevice) {
        this.glDevice = glDevice;
        if (glDevice != null && glDevice.getImei() != null) {
            imei = glDevice.getImei();
            String imei = glDevice.getImei();
            String gl_id = glDevice.getGl_id();
            String gl_name = glDevice.getGl_name();
            String ip = glDevice.getIp();
            String admin = glDevice.getAdmin();
            String personal = glDevice.getPersonal();
            boolean local = glDevice.getLocal();
            boolean bind_status = glDevice.getBind_status();
            boolean online_status = glDevice.getOnline_status();
            String info = BuildStringUtil.buildString(
                    "imei=", this.imei + "", "\r\n"
                    , "imei=", imei, "\r\n"
                    , "gl_id=", gl_id, "\r\n"
                    , "gl_name=", gl_name, "\r\n"
                    , "ip=", ip, "\r\n"
                    , "1".equals(personal) ? "私有设备" : "公有设备", "\r\n"
                    , "1".equals(admin) ? "管理员" : "普通用户", "\r\n"
                    , online_status ? ((local ? "局域网" : "远程") + "在线") : "离线", "\r\n"
                    , bind_status ? "已绑定" : "未绑定", "\r\n"
                    , "admin=", admin, "\r\n"
            );
            deviceInfoTv.setText(info);

            bindBtn.setText(bind_status ? "解绑" : "绑定");

        } else {
            Toastor.showToast("设备已经不存在");
            finish();
        }
    }

    @Subscriber(tag = AppConstant.REC_THROUGH_DATA)
    private void onRecData(String recIdAndData) {
        int indexOf = recIdAndData.indexOf("-");
        String idStr = recIdAndData.substring(0, indexOf);
        String recData = recIdAndData.substring(indexOf + 1, recIdAndData.length());
        if (glDevice == null) {
            return;
        }
        if (glDevice.getImei().equals(idStr)) {
            String hms = getCurrentTimeHMS();
            receiveServerMsgTv.setText("收到透传:" + recData + "。--于" + hms);
        }
    }

    @OnClick({
            R.id.bind_btn,
            R.id.test_btn,
            R.id.send2device_btn
    })
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.bind_btn://绑定
                String btnText = bindBtn.getText().toString().trim();
                switch (btnText) {
                    case "绑定":
                        bind();
                        break;
                    case "解绑":
                        unbind();
                        break;
                }
                break;
            case R.id.send2device_btn://发送透传
                String msg = send2deviceEt.getText().toString().trim();
                send2device(msg, new GlCallback() {
                    @Override
                    public void done(int resultCode) {
                        if (resultCode == GlResultCode.GL_CALLBACK_CODE_SUCCESS) {
                            send2deviceEt.setText("发送成功");
                        } else {
                            send2deviceEt.setText("");
                            send2deviceEt.setHint("发送失败:" + resultCode);
                        }
                    }
                });
                break;
            case R.id.test_btn:
                int length = loopMsg.length();
                if (len != length) {
                    loopMsg = "";
                    for (int i = 0; i < len - 3 - (totalTimes + "").length(); i++) {
                        loopMsg = "0" + loopMsg;
                    }
                }

                loop = !loop;
                if (loop) {//开启
                    new Thread(loopRunnable).start();
                    testBtn.setText(TEXT_CLOSE_TEST);
                } else {//关闭
                    testBtn.setText(TEXT_OPEN_TEST);
                }


                break;
        }
    }

    @OnClick(R.id.set_hz_btn)
    void onClickSetHz(View view) {
        String lenStr = setHzEt.getText().toString().trim();
        if (TextUtils.isEmpty(lenStr)) {
            Toastor.showToast("不能为空");
            return;
        }

        try {
            sleep = Integer.parseInt(lenStr);
        } catch (Exception e) {
            Toastor.showToast("请输入正确数字");
            return;
        }

        Toastor.showToast("设置成功");
    }

    @OnClick(R.id.set_lenth_btn)
    void onClickSetLen(View view) {
        String lenStr = setLenthEt.getText().toString().trim();
        if (TextUtils.isEmpty(lenStr)) {
            Toastor.showToast("不能为空");
            return;
        }

        try {
            len = Integer.parseInt(lenStr);
        } catch (Exception e) {
            Toastor.showToast("请输入正确数字");
            return;
        }

        Toastor.showToast("设置成功");
    }

    /**
     * 获取当前的时间
     * 格式为:时分秒
     *
     * @return 返回格式化的时间
     */
    public static String getCurrentTimeHMS() {
        Calendar calendar = Calendar.getInstance();
        Date date = calendar.getTime();
        SimpleDateFormat sdformat = new SimpleDateFormat("HH:mm:ss", Locale.CHINESE);//24小时制
        return sdformat.format(date);
    }


    private void bind() {
        GlEngine.bindDevice(imei, new GlCallback() {
            @Override
            public void done(int resultCode) {
                if (resultCode == GlResultCode.GL_CALLBACK_CODE_SUCCESS) {
                    bindBtn.setText("解绑");
                    Toastor.showToast("绑定成功");
                } else {
                    Toastor.showToast("绑定失败");
                }
            }
        });
    }

    private void unbind() {
        GlEngine.unbindDevice(imei, new GlCallback() {
            @Override
            public void done(int resultCode) {
                if (resultCode == GlResultCode.GL_CALLBACK_CODE_SUCCESS) {
                    bindBtn.setText("绑定");
                    Toastor.showToast("解绑成功");
                } else {
                    Toastor.showToast("解绑失败");
                }
            }
        });
    }


    private void send2device(String payloadData, GlCallback callback) {
        if (TextUtils.isEmpty(payloadData)) {
            Toastor.showToast("消息不能为空");
            return;
        }
        GlEngine.sendPayloadToDevice(imei, payloadData.getBytes(), callback);
    }

}
